/**
 * 
 */
package com.skn;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author HuuGia
 *
 */
public class MailSender {

	public static void sendSimpleMail (String from, String to, String subject, String body, String mailhost, String username, String password) throws MessagingException {
		Properties props = System.getProperties();
		
		// Attempt to authenticate the user with the AUTH command
		props.put("mail.smtp.auth", true);
		
        // Get a Session object
        Session session = Session.getInstance(props, null);
        
        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            msg.setFrom();
        }
        
        // Set the subject
        msg.setSubject(subject);
        msg.setText(body);

        //msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // Using SMTPTransport to send email with authentication 
        Transport transport = session.getTransport("smtps");
        transport.connect(mailhost, username, password);
        // Using method sendMessage of SMTPTransport 
        transport.sendMessage(msg, InternetAddress.parse(to, false));
        transport.close();

        System.out.println("\nMail was sent successfully.");
    }

	public static void getInboxMail (String mailhost, String username, String password) throws MessagingException, IOException {
		Properties props = new Properties();
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        //Set manual Properties
        props.setProperty( "mail.pop3.socketFactory.class", SSL_FACTORY);
        props.setProperty( "mail.pop3.socketFactory.fallback", "false");
        props.setProperty( "mail.pop3.port", "995");
        props.setProperty( "mail.pop3.socketFactory.port", "995");
        props.put("mail.pop3.host", mailhost);

	    String provider = "pop3s";

	    Session session = Session.getDefaultInstance(props, null);
	    Store store = session.getStore(provider);
	    store.connect(mailhost, username, password);

	    Folder inbox = store.getFolder("INBOX");
	    
	    if (inbox == null) {
	      System.out.println("No INBOX");
	      System.exit(1);
	    }
	    inbox.open(Folder.READ_ONLY);

	    Message[] messages = inbox.getMessages();
	    for (int i = 0; i < messages.length; i++) {
	      System.out.println("Message " + (i + 1));
	      messages[i].writeTo(System.out);
	    }
	    inbox.close(false);
	    store.close();
	  }
}
